﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Media.Imaging;
using FunstreamTV.Model.Subscribe;
using FunstreamTV.Tools;
using FunstreamTV.ViewModel;
using static System.String;

namespace FunstreamTV.Converters
{
    public class TextToRichConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var rtb = new RichTextBlock();
            var block = new Paragraph();
            var message = value.ToString();

            //string message = "Here is testing message :peka: :grumpy: http://google.com  : goodgame.ru ya.ru/sdfsdf/dfsdf?xx=gg ::: : :peka: :gglord:";
            Debug.WriteLine(message + "\n");

            var collection = MultiRegexpParser.Parse(
                message, new[] { @"[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)", ":[a-zA-Z_-]+?:" });

            // все блоки по порядку
            foreach (var c in collection)
            {
                // тип, текст или результат регулярки
                switch (c.Type)
                {
                    // Если резудьтат регулярки
                    case RegexpResultType.Match:
                        // ID соответствует номерурегулярки в списке, 0 - ссылки, 1 - смайлы
                        switch (c.ExpressionId)
                        {
                            case 0: // ссылки   
                                try
                                {
                                    var hyperlink = new Hyperlink { NavigateUri = new Uri(c.ExpMatch.Value) };
                                    hyperlink.Inlines.Add(new Run { Text = c.ExpMatch.Value });
                                    block.Inlines.Add(hyperlink);
                                }
                                catch
                                {
                                    var hyperlink = new Hyperlink { NavigateUri = new Uri("http://" + c.ExpMatch.Value) };
                                    hyperlink.Inlines.Add(new Run { Text = c.ExpMatch.Value });
                                    block.Inlines.Add(hyperlink);
                                }
                                Debug.WriteLine("Link: " + c.ExpMatch.Value);
                                break;
                            case 1: // смайлы
                                var smile = App.Smiles.FirstOrDefault(i => i.code.Equals(c.ExpMatch.Value.Replace(":", "")));
                                if (smile != null)
                                    block.Inlines.Add(new InlineUIContainer
                                    {
                                        Child = new Image { Source = new BitmapImage(new Uri(smile.FullUri)), Width = 30, Height = 30 }
                                    });
                                else
                                    block.Inlines.Add(new Run { Text = c.ExpMatch.Value });
                                Debug.WriteLine("Smile: " + c.ExpMatch.Value);
                                break;
                        }
                        break;
                    // Если текст
                    case RegexpResultType.Text:
                        block.Inlines.Add(new Run { Text = c.Value });
                        Debug.WriteLine("Text: " + c.Value);
                        break;
                }
            }

            //var matches = Regex.Matches(message, @":(.*?):");
            //int index = 0;
            //if (matches.Count == 0)
            //{
            //    block.Inlines.Add(new Run { Text = message });
            //}
            //foreach (Match match in matches)
            //{
            //    var temp = message.Substring(index, match.Index - index);
            //    var regex = new Regex(@":(.*?):");
            //    block.Inlines.Add(new Run { Text = regex.Replace(temp, "") });
            //    var smile = App.Smiles.FirstOrDefault(i => i.code.Equals(match.ToString().Replace(":", "")));
            //    if (smile != null)
            //        block.Inlines.Add(new InlineUIContainer
            //        {
            //            Child = new Image { Source = new BitmapImage(new Uri(smile.FullUri)), Width = 30, Height = 30 }
            //        });
            //    else
            //        block.Inlines.Add(new Run { Text = match.ToString() });

            //    index = match.Index;
            //}

            //var substring = message.Substring(index, message.Length - index);
            //block.Inlines.Add(new Run { Text = new Regex(@":(.*?):").Replace(substring, "") });

            ////ссылки
            //foreach (Run run in block.Inlines.Where(i => i is Run))
            //{
            //    var text = run.Text;
            //    var matchLinks = Regex.Matches(text, @"[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)", RegexOptions.IgnoreCase);
            //    int index2 = 0;
            //    foreach (Match matchLink in matchLinks)
            //    {
            //        var simpleText = text.Substring(index2, matchLink.Index - index2);
            //        block.Inlines.Add(new Run { Text = simpleText.Replace(matchLink.ToString(), "") });

            //        try
            //        {
            //            var link = new Hyperlink { NavigateUri = new Uri(matchLink.ToString()) };
            //            link.Inlines.Add(new Run { Text = matchLink.ToString() });
            //            block.Inlines.Add(link);
            //        }
            //        catch
            //        {
            //            block.Inlines.Add(new Run { Text = matchLink.ToString() });
            //        }
            //        index2 = matchLink.Index;
            //    }
            //}

            rtb.Blocks.Add(block);
            return rtb;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return Empty;
        }
    }
}
